package com.bcu.cn.onlineexamsystem.questionmanage.controller;

import com.bcu.cn.onlineexamsystem.questionmanage.entity.QuestionManage;
import com.bcu.cn.onlineexamsystem.questionmanage.service.QuestionManageService;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Course;
import com.bcu.cn.onlineexamsystem.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher/question")
public class QuestionManageController {
    
    private static final Logger logger = LoggerFactory.getLogger(QuestionManageController.class);
    
    @Autowired
    private QuestionManageService questionManageService;
    
    @GetMapping("/manage")
    public String managePage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "redirect:/login";
        }
        
        // 获取按课程分组的试题
        Map<Course, List<QuestionManage>> questionsByCourse = questionManageService.getQuestionsGroupByCourse(user.getUserId());
        logger.info("获取到的课程-试题映射: {}", questionsByCourse);
        
        // 记录每个课程的试题数量
        questionsByCourse.forEach((course, questions) -> {
            logger.info("课程[{}]下的试题数量: {}", course.getCourseName(), questions.size());
        });
        
        model.addAttribute("questionsByCourse", questionsByCourse);
        return "teacher/question/manage";
    }
    
    @GetMapping("/add")
    public String addQuestionPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "redirect:/login";
        }
        
        // 获取教师的课程列表
        List<Course> courses = questionManageService.getTeacherCourses(user.getUserId());
        logger.info("教师[{}]的课程列表: {}", user.getUserId(), courses);
        
        model.addAttribute("courses", courses);
        return "teacher/question/add";
    }
    
    @PostMapping("/add")
    @ResponseBody
    public String addQuestion(@RequestBody QuestionManage question, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        question.setTeacherId(user.getUserId());
        logger.info("添加试题信息: {}", question);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "未登录";
        }
        
        question.setTeacherId(user.getUserId());
        if (questionManageService.addQuestion(question)) {
            logger.info("试题添加成功");
            return "success";
        }
        logger.warn("试题添加失败");
        return "添加失败";
    }
    
    @GetMapping("/edit/{id}")
    public String editQuestionPage(@PathVariable Long id, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        logger.info("编辑试题ID: {}", id);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "redirect:/login";
        }
        
        QuestionManage question = questionManageService.getQuestionById(id);
        logger.info("获取到的试题信息: {}", question);
        
        if (question == null || !question.getTeacherId().equals(user.getUserId())) {
            logger.warn("试题不存在或无权限编辑");
            return "redirect:/teacher/question/manage";
        }
        
        // 获取教师的课程列表
        List<Course> courses = questionManageService.getTeacherCourses(user.getUserId());
        logger.info("教师[{}]的课程列表: {}", user.getUserId(), courses);
        
        // 处理options字段，转为A|B|C|D格式字符串
        String optionsStr = "";
        if (question.getOptions() != null) {
            String options = question.getOptions();
            if (options.startsWith("[")) {
                // JSON数组
                try {
                    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    java.util.List<String> optionList = mapper.readValue(options, java.util.List.class);
                    optionsStr = String.join("|", optionList);
                } catch (Exception e) {
                    logger.error("选项JSON解析失败", e);
                    optionsStr = "";
                }
            } else {
                optionsStr = options;
            }
        }
        model.addAttribute("optionsStr", optionsStr);
        model.addAttribute("courses", courses);
        model.addAttribute("question", question);
        return "teacher/question/edit";
    }
    
    @PostMapping("/edit")
    @ResponseBody
    public String editQuestion(@RequestBody QuestionManage question, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        logger.info("编辑试题信息: {}", question);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "未登录";
        }
        
        QuestionManage existingQuestion = questionManageService.getQuestionById(question.getQuestionId());
        logger.info("原试题信息: {}", existingQuestion);
        
        if (existingQuestion == null || !existingQuestion.getTeacherId().equals(user.getUserId())) {
            logger.warn("试题不存在或无权限修改");
            return "无权限修改";
        }
        
        question.setTeacherId(user.getUserId());
        // 处理options字段，转为JSON数组字符串
        if (question.getOptions() != null && !question.getOptions().trim().isEmpty()) {
            String[] arr = question.getOptions().split("\\|");
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String jsonOptions = mapper.writeValueAsString(arr);
                question.setOptions(jsonOptions);
            } catch (Exception e) {
                logger.error("选项转JSON失败", e);
                question.setOptions("[]");
            }
        } else {
            question.setOptions("[]");
        }
        if (questionManageService.updateQuestion(question)) {
            logger.info("试题更新成功");
            return "success";
        }
        logger.warn("试题更新失败");
        return "修改失败";
    }
    
    @PostMapping("/delete/{id}")
    @ResponseBody
    public String deleteQuestion(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        logger.info("删除试题ID: {}", id);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.warn("用户未登录或非教师角色");
            return "未登录";
        }
        
        QuestionManage question = questionManageService.getQuestionById(id);
        logger.info("获取到的试题信息: {}", question);
        
        if (question == null || !question.getTeacherId().equals(user.getUserId())) {
            logger.warn("试题不存在或无权限删除");
            return "无权限删除";
        }
        
        if (questionManageService.deleteQuestion(id, user.getUserId())) {
            logger.info("试题删除成功");
            return "success";
        }
        logger.warn("试题删除失败");
        return "删除失败";
    }
} 